package com.logic.saas.action;


import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import com.logic.saas.enums.ConstantEnum;
import com.logic.saas.enums.SessionKey;
import com.logic.saas.exception.ValidationException;
import com.logic.saas.pojo.LoginLog;
import com.logic.saas.pojo.User;
import com.logic.saas.service.security.LoginLogService;
import com.logic.saas.service.security.UserService;
import com.logic.saas.util.AddLog;
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;



public class LoginAction extends BaseAction {
	private static final long serialVersionUID = 6818625860651967510L;
	private User user;
	@Autowired
	private UserService userService;
	@Autowired
	private LoginLogService loginLogService;
	
	//登陆类型，adminLogin or 其它
	private String loginType;
	
	@Actions({  
		@Action(value="login", results={@Result(name="success", location="/WEB-INF/jsp/common/login.jsp")}),  
		@Action(value="/admin/login", results={@Result(name="success", location="/WEB-INF/jsp/admin/login.jsp")})     
	}) 
	@SkipValidation
    public String execute() throws Exception {
    	AddLog.addToLog(this.getClass(), AddLog.INFO, "forward to login page.....");
        return SUCCESS;
    }

	@Action("loginSubmit")
	@InputConfig(methodName = "handleInputError")
	public String login(){
		boolean loginSuccess = false;
		String errorMessage= this.getText("error.login.failed");
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		if (user != null && StringUtils.isNotBlank(user.getShortName()) && StringUtils.isNotBlank(user.getPassword())){
			try {
				user = userService.findUserByNamePsw(user.getShortName(), user.getPassword());
				if (user != null && user.getId() != null) {
					AddLog.addToLog(this.getClass(), AddLog.INFO, "User log into system successfully.");
					//记录登录信息到log表
					LoginLog loginLog = new LoginLog();
					loginLog.setLoginTime(new Timestamp(new Date().getTime()));
					loginLog.setUser(user);
					loginLog.setIp(this.request.getRemoteAddr());
					loginLog.setSessionId(this.request.getSession().getId());
					loginLogService.insertLoginlog(loginLog);
					
					//获取跳转到登陆界面之前的页面地址，由拦截器提供
			        String  prePage = (String) session.get(ConstantEnum.PRE_LOGIN_PAGE.getValue());
			        session.clear();
			       
					session.put(SessionKey.USER, user);
					session.put(SessionKey.USERID, user.getId());
					
					loginSuccess = true;
			        if (StringUtils.isNotBlank(prePage)) {
			            //不是拦截器跳转到登陆页面的，直接访问登陆前页面
			        	resultMap.put(ConstantEnum.PRE_LOGIN_PAGE.getValue(), prePage);
			        }
				}else{
					errorMessage = this.getText("error.wrong.username_or_paw");
				}
			}catch (DataAccessException e) {
				errorMessage = errorMessage + " : " + this.handelDataAccessException(e);
				AddLog.addToLog(this.getClass(), AddLog.ERROR, "login error"+e.getMessage());
			}catch(ValidationException ve){
				errorMessage = ve.getMessage();
			}catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			if(user == null){
				errorMessage = this.getText("error.wrong.username_or_paw");
			}else if(StringUtils.isBlank(user.getShortName())){
				errorMessage = this.getText("msg.username.input");
			}else{
				errorMessage = this.getText("msg.userpaw.input");
			}
		}
		
		if(!loginSuccess){
			resultMap.put(ConstantEnum.ERROR_MSG.getValue(),errorMessage);
		}
		resultMap.put(ConstantEnum.OPERATE_SUCCESS.getValue(), loginSuccess);
		this.setResult(resultMap);
		return JSON;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getLoginType() {
		return loginType;
	}

	public void setLoginType(String loginType) {
		this.loginType = loginType;
	}
	
}
